import 'package:flutter/material.dart';
import 'package:my_flutter_tool/modle/app_state.dart';
import 'package:my_flutter_tool/widgets/app_divider.dart';
import 'package:my_flutter_tool/widgets/loaders/dance_loader.dart';
import 'package:my_flutter_tool/widgets/loaders/hor_loader.dart';
import 'package:my_flutter_tool/widgets/refresh_view.dart';

///列表刷新/加载视图
class RefreshLoadView<T> extends StatefulWidget {
  ///每页数据条数，默认每页10条
  final int pageSize;

  ///滚动控制器
  final ScrollController scrollController;

  ///项目构建器
  ///* `index` 索引
  ///* `modle` 数据模型，使用时需要自行进行强转
  ///* `final User user = modle as User;`
  final Widget Function(int index, dynamic modle) itemBuilder;

  ///分隔符构建器
  final Widget Function(BuildContext context, int index) separatorBuilder;

  ///刷新事件
  ///* `size` 每页数据条数
  final Future<List<T>> Function(int size) onRefresh;

  ///加载事件
  ///* `page` 当前分页索引
  ///* `size` 每页数据条数
  final Future<List<T>> Function(int page, int size) onLoad;

  const RefreshLoadView({
    Key key,
    this.pageSize = 10,
    @required this.itemBuilder,
    this.separatorBuilder,
    @required this.onRefresh,
    @required this.onLoad,
    this.scrollController,
  }) : super(key: key);

  @override
  _RefreshLoadViewState<T> createState() => _RefreshLoadViewState<T>();
}

class _RefreshLoadViewState<T> extends State<RefreshLoadView> {
  ///状态
  PageState _pageState;

  ///对象数据列表
  List<T> _dataList;

  ///请求分页
  int _page;

  ///是否没有更多数据了
  bool _isNoMore;

  ///是否正在加载更多
  bool _isLoading;

  ///滚动控制
  ScrollController _controller;

  @override
  void setState(fn) {
    if (this.mounted) super.setState(fn);
  }

  @override
  void initState() {
    super.initState();
    _dataList = List<T>();
    _pageState = PageState.loading;
    _page = 1;
    _isNoMore = false;
    _isLoading = false;
    _controller = widget.scrollController ?? ScrollController();

    _refresh();
  }

  ///刷新
  Future<void> _refresh() async {
    _page = 1;
    _isNoMore = false;

    _dataList = await widget.onRefresh(widget.pageSize);

    if (_dataList.length == 0) {
      _pageState = PageState.empty;
    } else {
      _pageState = PageState.normal;
    }
    setState(() {});
  }

  ///加载更多
  Future<void> _loadMore() async {
    if (_isLoading) return;

    _isLoading = true;

    _page++;

    final List<T> _temp = await widget.onLoad(_page, widget.pageSize);

    if (_temp.length == 0) {
      ///没有更多了
      _page--;
      setState(() {
        _isNoMore = true;
      });
    } else {
      _dataList.addAll(_temp);
      setState(() {});
    }

    _isLoading = false;
  }

  @override
  Widget build(BuildContext context) {
    return [
      const Center(child: DanceLoader()),
      RefreshView(
        onRefresh: _refresh,
        child: ListView.separated(
          controller: _controller,
          itemCount: _dataList.length + 1,
          physics: const BouncingScrollPhysics(),
          itemBuilder: (BuildContext context, int index) =>
              _dataList.length == index
                  ? _buildLoader
                  : widget.itemBuilder(index, _dataList[index]),
          separatorBuilder:
              widget.separatorBuilder ?? (_, __) => const AppDivider(),
        ),
      ),
      RefreshView(
        onRefresh: _refresh,
        child: Container(
          height: 100,
          color: Colors.red,
          child: Text('没有数据'),
        ),
      ),
    ][_pageState.index];
  }

  ///构建加载更多视图
  Widget get _buildLoader {
    _loadMore();

    return Container(
      height: 50,
      alignment: Alignment.center,
      child: _isNoMore ? Text('没有更多数据了') : const HorLoader(),
    );
  }
}
